﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Collections.Specialized;

namespace Tencent.OA.App
{
    public class PagerInfoModelBinder : IModelBinder
    {
        private const string PAGE_INDEX_NAME = "page";
        private const string PAGE_SIZE_NAME = "size";

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");

            NameValueCollection queryStrings = controllerContext.HttpContext.Request.QueryString;
            int pageIndex = 0;
            if (TryGetValueFromQueryString(queryStrings, PAGE_INDEX_NAME, out pageIndex))
            {
                // url中显示的索引为页码，需减去1.
                if (pageIndex > 0)
                    pageIndex -= 1;
            }

            int pageSize;
            if (!TryGetValueFromQueryString(queryStrings, PAGE_SIZE_NAME, out pageSize))
            {
                PagerSection config = TencentConfigurationSectionGroup.GetSection<PagerSection>(PagerSection.PagerSectionKey);
                pageSize = config.PagerDefaultPageSize;
            }

            return new PagerInfo(pageIndex, pageSize);
        }

        private bool TryGetValueFromQueryString(NameValueCollection queryStrings, string key, out int value)
        {
            if (queryStrings.AllKeys.Contains(key))
            {
                return int.TryParse(queryStrings[key], out value);
            }
            value = default(int);
            return false;
        }
    }
}
